/*******************************************************************************
 * Package: com.song.flowable.listener
 * Type:    ProcessDueTimeListener
 * Date:    2023-11-20 15:37
 *
 * Copyright (c) 2023 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.flowable.listener;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngines;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.task.api.Task;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


/**
 * 功能描述：ExecutionListener 执行监听器
 *执行监听器是与执行流程实例的过程（Execution）相关联的，可以在流程启动、节点进入、节点离开等不同阶段触发。
 * @author Songxianyang
 * @date 2023-11-20 15:37
 */
@Component
@Slf4j
public class ProcessDueTimeListener implements ExecutionListener, ApplicationContextAware {

    private static final long serialVersionUID = 3610847321776743526L;
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ProcessDueTimeListener.applicationContext = applicationContext;
    }

    private TaskService taskService;

    private TaskService getBean(){
        if(taskService==null){
            taskService=applicationContext.getBean(TaskService.class);
        }
        return taskService;
    }




    @Override
    public void notify(DelegateExecution execution) {
        // 获取TaskService对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService service = processEngine.getTaskService();
        Task task = service.createTaskQuery().processInstanceId(execution.getProcessInstanceId()).singleResult();
        // 填写退回原因
        service.addComment(task.getId(),task.getProcessInstanceId(),"超时自动审批！");
    }

}
